import { Component, Input, OnInit } from '@angular/core';
import { FirstLevel } from '../sift/firstLevel.model';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { ModalController, AlertController, IonContent } from '@ionic/angular';
import { OpenModalChooseConditionComponent } from '../open-modal-choose-condition/open-modal-choose-condition.component';
import { HttpService } from 'src/app/shared/service/http.service';
import { EventService } from 'src/app/shared/service/event.service';
import { NewFilterModalComponent } from '../new-filter-modal/new-filter-modal.component';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
//tslint:disable
@Component({
  selector: 'app-common-filter',
  templateUrl: './common-filter.component.html',
  styleUrls: ['./common-filter.component.scss'],
})
export class CommonFilterComponent implements OnInit {

  @Input() tagData;
  siftArr: FirstLevel[];
  siftTypeArr: any;
  siftWidth: any;
  showName: any;
  key: any;
  type: any;
  useSiftComponent = false;
  siftHomeCssStyle: any;
  siftListCssStyle: any;
  constructor(private ags: AppGlobalService,
    private httpService: HttpService,
    private eventService: EventService,
    private pageModalService: PageModalService,
    private modalController: ModalController) {
    this.eventService.eventEmit.on("updateCommonFilter", (obj) => {
      // const reqTag = localStorage.getItem("updateCommonFilterTag");
      // if (reqTag !== undefined && reqTag !== null) {
      //   localStorage.removeItem("updateCommonFilterTag");
      if (obj) {
        this.initFilterTag(obj);
      }
      // }
    });

  }

  initFilterTag(obj) {
    try {
      this.tagData.filterItems = obj.filterItems;
      this.siftArr = [];
      this.tagData.filterItems.forEach(element => {
        this.siftArr.push(element);
      });
      for (let i = 0; i < this.siftArr.length; i++) {
        if (this.siftArr[i].dropDownList) {
          if (this.siftArr[i].dropDownList.displayName) {
          }
          if (this.siftArr[i].type === "filter") {
            this.ags.scResult.filter[this.siftArr[i].name] = this.siftArr[i].dropDownList.value;
          }
        } else if (this.siftArr[i].type === "link" && this.siftArr[i].display && this.siftArr[i].display.displayName.length) {
          this.siftArr[i].title = this.siftArr[i].display.displayName;
          this.ags.scResult.filter[this.siftArr[i].name] = this.siftArr[i].display.value;
        }
      }
      if (this.tagData.filterType) {
        this.siftTypeArr = this.tagData.filterType;
        if (this.siftTypeArr.length > 0) {
          this.siftWidth = ((100 - this.siftTypeArr.length * 2) / this.siftTypeArr.length) + "%";
        }
        this.ags.scResult.showName = this.showName;
      }
      // callbackFuncntion();
    } catch (error) {

    }
  }

  ngOnInit() {
    try {

      if (this.tagData.filterItems
        && this.tagData.filterItems.length > 0
        && this.tagData.filterItems[0].link !== undefined
        && this.tagData.filterItems[0].link.params
        && this.tagData.filterItems[0].link.params.siftHomeCssStyle !== undefined
      ) {
        this.siftHomeCssStyle = this.tagData.filterItems[0].link.params.siftHomeCssStyle;
      }

      if (this.tagData.filterItems
        && this.tagData.filterItems.length > 0
        && this.tagData.filterItems[0].link !== undefined
        && this.tagData.filterItems[0].link.params
        && this.tagData.filterItems[0].link.params.siftListCssStyle !== undefined
      ) {
        this.siftListCssStyle = this.tagData.filterItems[0].link.params.siftListCssStyle;
      }


      if (this.tagData.filterItems
        && this.tagData.filterItems.length > 0
        && this.tagData.filterItems[0].link !== undefined
        && this.tagData.filterItems[0].link.params
        && this.tagData.filterItems[0].link.params.useSiftComponent !== undefined
        && this.tagData.filterItems[0].link.params.useSiftComponent === 'true'
      ) {

        this.useSiftComponent = true;
      } else {
        this.siftArr = [];
        this.tagData.filterItems.forEach(element => {
          this.siftArr.push(element);
          // console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	   ', element);
        });
        for (let i = 0; i < this.siftArr.length; i++) {
          if (this.siftArr[i].dropDownList) {
            if (this.siftArr[i].dropDownList.displayName) {
            }
            if (this.siftArr[i].type === "filter") {
              // this.result.filter[this.siftArr[i].name] = this.siftArr[i].dropDownList.value;
            }
          } else if (this.siftArr[i].type === "link" && this.siftArr[i].display && this.siftArr[i].display.displayName.length) {
            this.siftArr[i].title = this.siftArr[i].display.displayName;
            // this.result.filter[this.siftArr[i].name] = this.siftArr[i].display.value;
          }
        }
        if (this.tagData.filterType) {
          this.siftTypeArr = this.tagData.filterType;
          if (this.siftTypeArr.length > 0) {
            this.siftWidth = ((100 - this.siftTypeArr.length * 2) / this.siftTypeArr.length) + "%";
          }
          // this.result.showName = this.showName;
        }
      }



    } catch (error) {

    }
  }

  siftEventForNewStyle(obj) {
    try {
      this.key = obj.name;
      this.type = obj.type;
      if (obj.link && obj.link.params && obj.link.params.cssType && obj.link.params.cssType === 'secondaryLinkage') { // 1.9.0 改动 新增类型 行业以及区域 二级联动
        this.getIndustryData(obj, (data) => {
          data.formType = 'LJ'; // 类型
          data.max = 5; // 给个默认值
          data.value = null;
          data.cssType = 'secondaryLinkage';
          if (obj.link.params.max !== undefined) {
            data.max = parseInt(obj.link.params.max);
          }
          if (obj.link.params.tip1 !== undefined) {
            data.tip1 = obj.link.params.tip1;
          }
          if (obj.link.params.tip2 !== undefined) {
            data.tip2 = obj.link.params.tip2;
          }
          if (obj.link !== undefined) {
            data.link = obj.link;
          }
          this.openModalForSecondaryLinkage(obj, data, 1); // 行业区域二级联动
        });
      } else if (obj.link && obj.link.params && obj.link.params.cssType && obj.link.params.cssType === 'streamingLayout') { // 1.9.0 改动新增类型 流式 布局
        obj.formType = 'LJ'; // 类型
        obj.cssType = 'streamingLayout';
        this.openModalForSecondaryLinkage(obj, obj, 1); // 流式按钮布局

      } else if (obj.link && obj.link.params && obj.link.params.cssType && obj.link.params.cssType === 'rangeStreamingLayout') { // 1.9.20 改动新增服务时间范围 流式布局
        obj.formType = 'LJ'; // 类型
        obj.cssType = 'rangeStreamingLayout';
        this.openModalForSecondaryLinkage(obj, obj, 1); // 改动新增服务时间范围 流式布局

      } else if (obj.link && obj.link.params && obj.link.params.cssType && obj.link.params.cssType === 'customArea') { // 1.9.0 改动新增类型 自定义面积
        obj.formType = 'LJ'; // 类型
        obj.cssType = 'customArea';
        this.openModalForSecondaryLinkage(obj, obj, 1); // 自定义面积
      } else if (obj.cssStyle === 'new_semicircle') {
        this.getIndustryData(obj, (data) => {
          this.openModalForChoosenCondition(obj, data, 1); // 联动
        });
      } else if (obj.link && obj.link.params.cssType === 'openPage') {
        this.openPage(obj.link)
      } else {
        const singleData = { data: [], value: obj.dropDownList.item[0].value };
        if (this.key === "order") {
          obj.dropDownList.item.forEach(element => {
            singleData.data.push({ value: element.sorts, label: element.displayName });
          });
        } else {
          obj.dropDownList.item.forEach(element => {
            const tempData = { value: element.value, label: element.displayName };
            if (element.min && element.max) {
              tempData.value = element.min + ',' + element.max;
            }
            singleData.data.push(tempData);
          });
        }
        this.openModalForChoosenCondition(obj, singleData, 0);
      }
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  async openModalForSecondaryLinkage(source, obj, selectType) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: "openmodal-secondary-linkage",
      component: NewFilterModalComponent,
      componentProps: { tagData: obj, type: selectType, value: obj }
    });
    modal.onDidDismiss().then((data) => {
      console.log('onDidDismiss===', data);
      const value = data.data;
      if (value !== undefined) {
        // source.title = value.itemdata.label;
        // obj.value = value.itemdata.value;

        console.log('cssType=', obj.cssType);
        let valueArray = [];
        let labelArray = [];
        if (obj.cssType === 'secondaryLinkage') { // 行业 区域 二级联动
          if (value.length > 0) {
            value.forEach(element => {
              labelArray.push(element.label);
              valueArray.push(element.value);
            });
          }
          obj.value = valueArray.toString();
        } else if (obj.cssType === 'streamingLayout') { // 整租 合租 流式布局
          if (value.length > 0) {
            value.forEach(element => {
              labelArray.push(element.displayName);
              valueArray.push(element.value);
            });
          }
          obj.value = valueArray.toString();
        } else if (obj.cssType === 'rangeStreamingLayout') { // 新增服务时间访问选择控件
          // 新增服务时间选择
          if (value.length > 0) {
            value.forEach(element => {
              labelArray.push(element.displayName);
              valueArray.push(element.value);
            });
          }
          obj.value = valueArray.toString();
        } else if (obj.cssType === 'customArea') { // 面积 自定义面积
          value.forEach(element => {
            labelArray.push(element.displayName);
            valueArray.push(element.value);
            obj.min = element.min;
            obj.max = element.max;
            obj.value = element.value;
          });
        }

        if (labelArray && labelArray.length !== 0) {
          source.title = labelArray.toString();
        }
        this.getResult(obj, value);
      }
    });
    await modal.present();
  }

  async openModalForChoosenCondition(source, obj, selectType) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: "openmodal-choose-condition",
      component: OpenModalChooseConditionComponent,
      componentProps: { tagData: obj, type: selectType }
    });
    modal.onDidDismiss().then((data) => {
      const value = data.data;
      if (value !== undefined && value.itemdata) {
        source.title = value.itemdata.label;
        obj.value = value.itemdata.value;
        this.getResult(obj, value.itemdata);
      }
    });
    await modal.present();
  }

  getResult(obj, value) {
    const pos = JSON.parse(localStorage.getItem("position"));
    const kFilter = "filter";
    const kType = "filter";
    const kOrder = "order";
    const kLocation = "location";
    const kStrSort = "sort";
    if (this.type === "filter") {
      if (obj.cssType !== undefined && (
        obj.cssType === 'secondaryLinkage'
        || obj.cssType === 'streamingLayout'
        || obj.cssType === 'rangeStreamingLayout'
        || obj.cssType === 'customArea')) {
        if (obj.link && obj.link.params && obj.link.params.opportunity_plugin_id) {
          this.ags.scResult['opportunity_plugin_id'] = obj.link.params.opportunity_plugin_id;
        }
        if (obj.cssType === 'secondaryLinkage') {
          this.ags.scResult[kFilter][this.key] = obj.value;
        } else if (obj.cssType === 'streamingLayout') {
          if (value !== undefined && value.length > 0) {
            // 单选 or 多选
            value.forEach(element => {
              this.ags.scResult[kFilter][element.newName] = { [element.newKey]: element.value };
            });
          }
        } else if (obj.cssType === 'rangeStreamingLayout') {
          // 新增 服务时间范围选择 
          if (value !== undefined && value.length > 0) {
            value.forEach(element => {
              this.ags.scResult[kFilter][element.newName] = { [element.newKey]: element.value };
            });
          }
        } else if (obj.cssType === 'customArea') {
          if (obj.min === '' && obj.max === '') {
            this.ags.scResult[kFilter][this.key] = obj.value;
          } else {
            if (obj.min !== undefined || obj.max !== undefined) {
              (obj.min === undefined || obj.min === null) ? obj.min = "0" : obj.min = obj.min;
              // 用户输入了最小值如果手动删除最大值已与产品沟通传空串            
              this.ags.scResult[kFilter][this.key] = obj.min + "," + (obj.max === undefined ? "" : obj.max === null ? "" : obj.max);
            } else {
              this.ags.scResult[kFilter][this.key] = obj.value;
            }
          }
        }
      } else {
        if (obj.min !== undefined || obj.max !== undefined) {
          (obj.min === undefined || obj.min === null) ? obj.min = "0" : obj.min = obj.min;
          // 用户输入了最小值如果手动删除最大值已与产品沟通传空串
          this.ags.scResult[kFilter][this.key] = obj.min + "," + (obj.max === undefined ? "" : obj.max === null ? "" : obj.max);
        } else {
          this.ags.scResult[kFilter][this.key] = obj.value;
        }
      }
    } else if (this.type === kOrder) {
      if (this.ags.scResult[kLocation]) {
        delete this.ags.scResult[kLocation];
      }
      const kSort = {};
      if (obj.value !== undefined) {
        obj.value.forEach(v => {
          kSort[v.field] = v.value;
        });
        this.ags.scResult[kOrder][kStrSort] = kSort;
      }
    }
    Object.keys(this.ags.scResult).forEach(element => {
      if (element !== 'order') {
        if (this.ags.scResult[element] === null) { delete this.ags.scResult[element]; }
      }
    });
    if (this.tagData.filterItems[0] && this.tagData.filterItems[0].link && this.tagData.filterItems[0].link.params.scListTagName) {
      this.eventService.eventEmit.emit(this.tagData.filterItems[0].link.params.scListTagName + 'AskForList', this.ags.scResult);
    } else {
      setTimeout(() => {
        localStorage.setItem(this.ags.scListTagName + 'AskForListTag', this.ags.scListTagName);
        this.eventService.eventEmit.emit(this.ags.scListTagName + 'AskForList', this.ags.scResult);
      }, 5);
    }
  }

  getIndustryData(item, callBackFunction) {
    const pos = JSON.parse(localStorage.getItem("position"));
    const params = {
      content: { code: item.ifCode && item.ifCode + "" === "1" ? pos.code : 0 },
      id: item.dropDownList.id,
      sessionId: localStorage.getItem('sessionId')
    };
    this.httpService.post('application/submit', params, res => {
      if (res.data.data) {
        res.data.value = res.data.data[0].value;
        res.data.label = res.data.data[0].label;
        callBackFunction(res.data);
      } else {
        this.ags.showToast(res.message, 2000, 'middle');
      }
    });
  }

  openPage(link) {
    this.pageModalService.openPage(link);
  }
}